package sample.xiaosong.violentrecursion;

import java.util.Stack;

/**
 * 不使用其他数据结构的情况下  逆序一个栈
 */
public class ReverseStack {

    /**
     * 递归函数，利用变量i，也就是系统递归栈来保存元素
     * @param stack 栈
     */
    public static void reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) {
            return;
        }
        int i = getAndRemoveLast(stack);
        reverse(stack);
        stack.push(i);
    }

    /**
     * 找到栈底元素并弹出
     * @param stack 栈
     * @return 栈底元素
     */
    public static int getAndRemoveLast(Stack<Integer> stack) {
        int result = stack.pop();
        if (stack.isEmpty()) {
            return result;
        } else {
            int last = getAndRemoveLast(stack);
            stack.push(result);
            return last;
        }
    }

    public static void main(String[] args) {
        Stack<Integer> test = new Stack<Integer>();
        test.push(1);
        test.push(2);
        test.push(3);
        test.push(4);
        test.push(5);
        System.out.println("================逆序前=================");
        while (!test.isEmpty()) {
            System.out.println(test.pop());
        }
        Stack<Integer> test1 = new Stack<Integer>();
        test1.push(1);
        test1.push(2);
        test1.push(3);
        test1.push(4);
        test1.push(5);
        reverse(test1);
        System.out.println("================逆序后=================");
        while (!test1.isEmpty()) {
            System.out.println(test1.pop());
        }
    }
}
